package com.haochang.chunkvod.controller.fragment.hostess;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseGridView;
import com.haochang.base.BaseListView;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.adapter.base.BaseAdapterHelper;
import com.haochang.chunkvod.controller.adapter.base.QuickAdapter;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.hostess.HostessInfo;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.tools.vod.other.GridViewUtil;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.SingleSelectionDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * created at 2016/8/25 11:03
 * 转包页面
 */
public class SubcontractFragment extends BaseFragment
{
	private BaseListView listView;//各种转包  房间分类
	private BaseTextView  sub_to_time, room_grant, tv_room_room_type, sub_room_type;
	private RelativeLayout grant, group_room_type;
	private LinearLayout group_sub_time;
	private String statementTime = "";
	private String currentRoom = "";
	private String roomType = "";//当前房型 名称
	private String roomTypeId = "";//当前计费房型id
	private String toRoomTypeId = "";//转到的计费房型id
	private ArrayList<HostessInfo> listRoom = new ArrayList<HostessInfo>();//可用房间list
	private QuickAdapter<HostessInfo> adapter;
	private ArrayList<DialogItemInfo> listRoomTypes = new ArrayList<DialogItemInfo>();//计费房型list
	private String token = "";

	private String billId;
	HostessData hostessData;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		roomTypeId = getArguments().getString(IntentKey.ROOM_TYPE_ID);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_subcontract, container,false);
		hostessData = new HostessData((BaseActivity) getActivity());
		initView(view);
		return view;
	}

	private void initView(View view)
	{
		Button room_sub_ok = (Button) view.findViewById(R.id.room_sub_ok);//底部确认
		BaseTextView sub_statement_time = (BaseTextView) view.findViewById(R.id.sub_statement_time);//转包时间
		group_sub_time = (LinearLayout) view.findViewById(R.id.group_sub_time);
		listView = (BaseListView) view.findViewById(R.id.lv_room);
		sub_to_time = (BaseTextView) view.findViewById(R.id.sub_to_time);
		room_grant = (BaseTextView) view.findViewById(R.id.room_grant);
		tv_room_room_type = (BaseTextView) view.findViewById(R.id.tv_room_room_type);
		sub_room_type = (BaseTextView) view.findViewById(R.id.sub_room_type);
		grant = (RelativeLayout) view.findViewById(R.id.grant);
		group_room_type = (RelativeLayout) view.findViewById(R.id.group_room_type);
		grant.setOnClickListener(baseClickListener);
		group_room_type.setEnabled(false);
		group_sub_time.setVisibility(View.GONE);
		group_room_type.setOnClickListener(baseClickListener);
		room_sub_ok.setOnClickListener(baseClickListener);
		billId = getArguments().getString(IntentKey.BILL_ID);
		roomType = getArguments().getString(IntentKey.ROOM_TYPE);
		listRoomTypes = getArguments().getParcelableArrayList(IntentKey.ROOM_TYPES);
		statementTime = getArguments().getString(IntentKey.EXP_TIME);
		sub_statement_time.setText(TimeUtils.getMinutesString(statementTime));
		sub_room_type.setText(roomType);
		initData();
		getData();
	}

	private void initData() {
		adapter = new QuickAdapter<HostessInfo>(getActivity(), R.layout.item_sub_list, listRoom)
		{
			@Override
			protected void convert(BaseAdapterHelper helper, HostessInfo item)
			{
				helper.setText(R.id.tv_title, item.getRoomType());
				BaseGridView grid = helper.getView(R.id.grid_sub_item);
				QuickAdapter gridAdapter = new QuickAdapter<HostessInfo>(getActivity(), R.layout.item_part_modify_grid_layout, item.getRooms())
				{
					@Override
					protected void convert(BaseAdapterHelper helper, final HostessInfo item)
					{
						helper.getView(R.id.img_del).setVisibility(View.GONE);
						helper.setText(R.id.tv_partName, item.getRoomNum());
						if (!TextUtils.isEmpty(currentRoom) && currentRoom.equals(item.getRoomId()))
						{
							helper.getView(R.id.tv_partName).setBackgroundResource(R.drawable.btn_red);
							((BaseTextView) helper.getView(R.id.tv_partName)).setTextColor(getResources().getColor(R.color.white));
						} else
						{
							helper.getView(R.id.tv_partName).setBackgroundResource(R.drawable.btn1);
							((BaseTextView) helper.getView(R.id.tv_partName)).setTextColor(getResources().getColor(R.color.color_282828));
						}

						helper.getView(R.id.tv_partName).setOnClickListener(new OnBaseClickListener()
						{
							@Override
							public void onBaseClick(View v)
							{
								currentRoom = item.getRoomId();
								toRoomTypeId = item.getRoomTypeId();
								for (int i = 0; i < listRoom.size(); i++)
								{
									boolean flg = false;
									HostessInfo info = listRoom.get(i);
									for (int j = 0; j < listRoom.get(i).getRooms().size(); j++)
									{
										if (!TextUtils.isEmpty(currentRoom) && currentRoom.equals(info.getRooms().get(j).getRoomId()))
										{
											flg = true;
											break;
										}
									}
									if (flg)
									{
										roomTypeId = info.getRoomTypeId();
										roomType = info.getRoomType();
										break;
									}
								}
								sub_room_type.setText(roomType);
								getMostExpectedTime(toRoomTypeId);
								adapter.replaceAll(listRoom);
							}
						});
					}
				};
				grid.setAdapter(gridAdapter);
				GridViewUtil.setListViewHeightBasedOnChildren(getActivity(), grid);
				gridAdapter.notifyDataSetChanged();
			}
		};
		listView.setAdapter(adapter);
	}

	private OnBaseClickListener baseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.grant:
				Intent intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
				intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.HOSTESS_GRANT);
				startActivityForResult(intent, IntentCode.HOSTESS_GRANT_REQUEST);
				break;
			case R.id.group_room_type:
				if (null != listRoomTypes)
					for (DialogItemInfo info : listRoomTypes)
					{
						Logger.e("roomTypeId:" + roomTypeId + "__info.getCode():" + info.getCode());
						info.setSelected(TextUtils.equals(roomTypeId, info.getCode()));
					}
				new SingleSelectionDialog.Builder(getActivity()).setTitle("计费房型")
						.setSingleChoiceItems(listRoomTypes, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								sub_room_type.setText(name);
								roomTypeId = code;
								sub_room_type.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));
							}
						}).createDialog(5).show();
				break;
			case R.id.room_sub_ok:
				//提交数据
				if (!TextUtils.isEmpty(currentRoom) && !TextUtils.isEmpty(billId) && !TextUtils.isEmpty(roomTypeId))
				{

					hostessData.postSubRoom(billId, currentRoom, roomTypeId, token, new HostessData.NoticeListener()
					{
						@Override
						public void onRequestSuccess(String notice)
						{
							if (!TextUtils.isEmpty(notice))
							{
								ToastUtils.showText(getActivity().getApplicationContext(), "转包成功");
								getActivity().finish();
							} else
							{
								ToastUtils.showText(getActivity(), "转包失败");
								//刷新数据
								getData();
								//刷新转包后房间的最长预结时间
								getMostExpectedTime(toRoomTypeId);
							}
						}

						@Override
						public void onFail(int errno, String errMsg)
						{

						}
					});
				} else
				{
					ToastUtils.showText(getActivity(), "请选择转入房间");
				}
				break;
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.HOSTESS_GRANT_REQUEST && resultCode == FragmentActivity.RESULT_OK && data != null)
		{
			token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			if (!TextUtils.isEmpty(token))
			{
				granted();
			}
		}
	}

	private void granted()
	{
		room_grant.setText("已通过");
		room_grant.setTextColor(getResources().getColor(R.color.color_4bbb4d));
		Drawable drawable = getResources().getDrawable(R.drawable.ic_success);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_success);
		if(null!=drawable){
		drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
		room_grant.setCompoundDrawables(drawable, null, null, null);
		room_grant.setCompoundDrawablePadding(DipPxConversion.dipToPx(getActivity(), 4));
		}
		room_grant.setEnabled(false);
		grant.setEnabled(false);
		tv_room_room_type.setTextColor(getActivity().getResources().getColor(R.color.color_282828));
		sub_room_type.setTextColor(getActivity().getResources().getColor(R.color.color_282828));
		group_room_type.setEnabled(true);
	}

	/**
	 * 获取数据并显示
	 */
	private void getData()
	{
		hostessData.requestEmptyRoomList(new HostessData.ResultResponseList<HostessInfo>()
		{
			@Override
			public void onRequestSuccess(List<HostessInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					listRoom.clear();
					adapter.replaceAll(listRoom);
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{

			}
		});

	}

	/**
	 * 获取转包后房间的最长预结时间
	 */
	private void getMostExpectedTime(String roomTyoeId)
	{
		hostessData.requestMostStatementTime(roomTyoeId, billId, new HostessData.StatementTimeListener()
		{
			@Override
			public void onRequestSuccess(String time, long serverTime)
			{
				if (!TextUtils.isEmpty(time))
				{
					group_sub_time.setVisibility(View.VISIBLE);
					//如果选中房间最长开房时间小于转包前预结时间，为选中房间最长开房时间
					if (TimeUtils.compareTime(statementTime, time))
					{
						sub_to_time.setText(TimeUtils.getMinutesString(time));
					} else
					{
						sub_to_time.setText(TimeUtils.getMinutesString(statementTime));
					}
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{

			}
		});
	}

}
